package nimo.elibrary;

import android.util.Log;
import android.widget.Toast;
import com.elibrary.BookstoreApplication;
import com.elibrary.R;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.NameValuePair;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.utils.URLEncodedUtils;
import org.apache.http.impl.client.DefaultHttpClient;

import java.io.IOException;
import java.io.InputStream;
import java.util.List;

/**
 * Created with IntelliJ IDEA.
 * User: Enkuso
 * Date: 12/10/12
 * Time: 12:14 PM
 * To change this template use File | Settings | File Templates.
 */
public class WebService {

    public static String STATUS_OK = "ok";
    public static String STATUS_FAIL = "fail";

    /**
     * WebAPI-д хүсэлт илгээж хариу авах
     *
     * @param url
     * @return
     */
    public static InputStream retrieveStream(String url, List<NameValuePair> nameValuePairs) {

        DefaultHttpClient client = new DefaultHttpClient();

        // GET-р илгээх өгөгдлийг хавсаргах
        String params = URLEncodedUtils.format(nameValuePairs, "utf-8");
        if(!url.endsWith("?"))
            url += "?";
        url += params;

        HttpGet getRequest = new HttpGet(url);

        try {
            //Log.w("WebService", "Requesting URL " + url);
            // GET request явуулах
            HttpResponse getResponse = client.execute(getRequest);
            final int statusCode = getResponse.getStatusLine().getStatusCode();

            if (statusCode != HttpStatus.SC_OK) {
                Log.w("WebService",
                        "Error " + statusCode + " for URL " + url);
                //Toast.makeText(BookstoreApplication.getAppContext(), R.string.server_connect_error, Toast.LENGTH_SHORT).show();
                return null;
            }

            HttpEntity getResponseEntity = getResponse.getEntity();
            return getResponseEntity.getContent();

        }
        catch (IOException e) {
            getRequest.abort();
            Log.w("WebService", "Error for URL " + url, e);
            //Toast.makeText(BookstoreApplication.getAppContext(), R.string.server_connect_error, Toast.LENGTH_SHORT).show();
        }

        return null;
    }

    /**
     * WebAPI-д HTTP POST method-р хүсэлт илгээж хариу авах
     *
     * @param url
     * @param nameValuePairs
     * @return
     */
    public static InputStream retrieveStreamPOST(String url, List<NameValuePair> nameValuePairs) {

        DefaultHttpClient client = new DefaultHttpClient();

        HttpPost postRequest = new HttpPost(url);

        try {
            // POST-р илгээх өгөгдлийг хавсаргах
            postRequest.setEntity(new UrlEncodedFormEntity(nameValuePairs));

            // POST request явуулах
            HttpResponse postResponse = client.execute(postRequest);
            final int statusCode = postResponse.getStatusLine().getStatusCode();

            if (statusCode != HttpStatus.SC_OK) {
                Log.w("WebService",
                        "Error " + statusCode + " for URL " + url);
                //Toast.makeText(BookstoreApplication.getAppContext(), "PAGE NOT FOUND!", Toast.LENGTH_SHORT).show();
                return null;
            }

            HttpEntity getResponseEntity = postResponse.getEntity();

            Log.w("WebService",
                    "Success " + statusCode + " for URL " + url);

            return getResponseEntity.getContent();

        }
        catch (IOException e) {
            postRequest.abort();
            Log.w("WebService", "Error for URL " + url, e);
            //Toast.makeText(BookstoreApplication.getAppContext(), R.string.server_connect_error, Toast.LENGTH_SHORT).show();
        }

        return null;
    }
}
